'use strict';

const {
  listToTree
} = require("../utils");
const Controller = require('egg').Controller;
function getNestedProperty(obj, path) {
  return path.split('.').reduce((current, key) => {
    return current && current[key] !== undefined ? current[key] : undefined;
  }, obj);
}
class BaseController extends Controller {
  constructor(ctx) {
    super(ctx);
    // Get service name from child class
    this.serviceName = this.constructor.serviceName;
    if (!this.serviceName) {
      throw new Error('Service name must be specified in child class');
    }
    this.service = getNestedProperty(this.ctx.service, this.serviceName);
  }
  async create() {
    const { ctx } = this;
    const payload = ctx.request.body;
    const result = await this.service.create(payload);
    ctx.success(result);
  }

  async show() {
    const { ctx } = this;
    const id = ctx.params.id;
    const result = await this.service.findById(id);
    if (!result) {
      ctx.error(500, '查询数据不存在');
      return
    }
    ctx.success(result);
  }

  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const payload = ctx.request.body;
    const result = await this.service.update(id, payload);
    ctx.success(result);
  }

  // Delete
  async destroy() {
    const { ctx } = this;
    const result = await this.service.delete(this.ctx.params.id);
    ctx.success(result);
  }
  afterFormatQuery(where, query) {
    return where;
  }
  /**
   * 格式化查询条件
   * @param {Object} query 原始查询条件
   * @returns {Object} 格式化后的查询条件
   */
  formatQuery(query) {
    const formattedQuery = {};
    const { Op } = this.app.Sequelize;
    for (let key in query) {
      // 跳过分页参数
      if (['pageNo', 'pageSize', 'sorter'].includes(key)) continue;

      const value = query[key];
      if (!value) continue;

      // 处理时间范围查询 [startTime, endTime]
      if (key.endsWith('TimeRange') && Array.isArray(value)) {
        const fieldName = key.replace('TimeRange', '');
        if (value[0]) {
          formattedQuery[fieldName] = {
            [Op.gte]: value[0]
          };
        }
        if (value[1]) {
          formattedQuery[fieldName] = {
            ...formattedQuery[fieldName],
            [Op.lte]: value[1]
          };
        }
        continue;
      }
      // 处理数组条件 IN查询
      if (Array.isArray(value)) {
        formattedQuery[key] = {
          [Op.in]: value
        };
        continue;
      }

      // 处理模糊查询
      if (key.endsWith('Like')) {
        const fieldName = key.replace('Like', '');
        formattedQuery[fieldName] = {
          [Op.like]: `%${value}%`
        };
        continue;
      }

      // 处理范围查询
      if (key.endsWith('Start')) {
        const fieldName = key.replace('Start', '');
        formattedQuery[fieldName] = {
          [Op.gte]: value
        };
        continue;
      }
      if (key.endsWith('End')) {
        const fieldName = key.replace('End', '');
        formattedQuery[fieldName] = {
          ...formattedQuery[fieldName],
          [Op.lte]: value
        };
        continue;
      }

      // 默认精确匹配
      formattedQuery[key] = value;
    }
    return this.afterFormatQuery(formattedQuery, query);
  }

  /**
   * 处理排序参数
   * @param {string} sorter 排序字符串，格式如 'field,order'
   * @returns {Array} 排序配置数组
   */
  formatOrder(sort) {
    if (!sort) return [['create_time', 'DESC']];
    const [field, order] = sort.split(',');
    return [[field, order.toUpperCase()]];
  }
  async index() {
    const { ctx } = this;
    const { pageNo = 1, pageSize = 10, sort, ...queryParams } = ctx.query;

    // 格式化查询条件
    const query = this.formatQuery(queryParams);
    // 处理排序
    const order = this.formatOrder(sort);
    const result = await this.service.page(
        query,
        { page: parseInt(pageNo), pageSize: parseInt(pageSize)},
        order,
    );

    ctx.success(result);
  }
  /**
   * 获取列表（不分页）
   */
  async list() {
    const { ctx } = this;
    const { sorter, ...queryParams } = ctx.query;

    // 格式化查询条件
    const query = this.formatQuery(queryParams);
    // 处理排序
    const order = this.formatOrder(sorter);
    console.log(query)
    const result = await this.service.list(query, order);
    ctx.success(result);
  }

  /**
   * 树结构
   * @returns {Promise<void>}
   */
  async tree() {
    const { ctx } = this;
    const query = this.formatQuery(ctx.query);

    // 获取所有分类列表
    const list = await this.service.list({
      ...query,
    });
    // 使用 dataValues 获取数据
    const plainList = list.map(item => item.get({ plain: true }));
    // 构建树形结构
    const tree = listToTree(plainList);
    // 返回树形结构
    ctx.success(tree);
  }
}

module.exports = BaseController;
